package com.lagou.code.service.impl;

import com.lagou.code.dao.IAuthCodeRepository;
import com.lagou.code.feign.EmailFeignClient;
import com.lagou.code.service.IAuthCodeService;
import com.lagou.common.pojo.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * created by kirito at 2020/7/12
 */
@Service
public class AuthCodeServiceImpl implements IAuthCodeService {

    @Autowired
    private IAuthCodeRepository authCodeRepository;

    @Autowired
    private EmailFeignClient emailFeignClient;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int validateCode(String email, String code) {
        List<AuthCode> authCodeList = authCodeRepository.findByEmailOrderByCreateTimeDesc(email);
        AuthCode authCode = authCodeList.get(0);
        try {
            if (authCode.getCode().equals(code)) {
                long now = System.currentTimeMillis();
                return now > sdf.parse(authCode.getExpireTime()).getTime() ? 2 : 0;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 1;
    }

    @Override
    public boolean createCode(String email) {
        AuthCode authCode = new AuthCode();
        String code = getRandomCode();
        long createTime = System.currentTimeMillis();
        long expireTime = createTime + 10 * 60 * 1000;
        authCode.setCode(code);
        authCode.setEmail(email);
        authCode.setCreateTime(sdf.format(new Date(createTime)));
        authCode.setExpireTime(sdf.format(new Date(expireTime)));
        authCodeRepository.save(authCode);
        // 调用邮件发送服务
        return emailFeignClient.sendAuthCode(email, code);
    }

    private String getRandomCode() {

        final Random r = new Random();
        int code = r.nextInt(999999);
        if (code < 100000) {
            code += 100000;
        }
        return String.valueOf(code);
    }
}
